package com.lanchetech.admin.service.impl;


import com.lanchetech.admin.service.BrandService;
import com.lanchetech.bean.request.PageReq;
import com.lanchetech.bean.response.BasePageResp;
import com.lanchetech.bean.response.BaseResp;
import com.lanchetech.bean.response.ResultData;
import com.lanchetech.bean.util.PageHelpUtil;
import com.lanchetech.dao.BrandMapper;
import com.lanchetech.dao.CategoryBrandMapper;
import com.lanchetech.entity.Brand;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class BrandServiceImpl implements BrandService {

    @Autowired
    BrandMapper brandMapper;

    @Autowired
    CategoryBrandMapper categoryBrandMapper;

    @Override
    public ResultData<BasePageResp<Brand>> getBrandPage(PageReq req) {
        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<Brand> list = brandMapper.findAllPage(req);
        return PageHelpUtil.buildPage(list, page);
    }

    @Override
    public BaseResp editBrand(Brand brand) {
        if (brand.getId() == null) {
            // 添加
            brand.setCreatedAt(new Date());
            brand.setUpdatedAt(new Date());
            brandMapper.insert(brand);
        } else {
            // 编辑
            brand.setUpdatedAt(new Date());
            brandMapper.updateByPrimaryKeySelective(brand);
            categoryBrandMapper.deleteByBrandId(brand.getId());
        }
        return new BaseResp();
    }

    @Override
    public ResultData<Brand> getBrandDetail(Long id) {
        return new ResultData<>(brandMapper.selectByPrimaryKey(id));
    }

    @Override
    public BaseResp deleteBrand(Long id) {
        brandMapper.deleteByPrimaryKey(id);
        return new BaseResp();
    }

    @Override
    public ResultData<List<Brand>> getBrandList() {
        return new ResultData<>(brandMapper.findAll());
    }
}